package ru.sushka.lunch.dao.files;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import ru.sushka.lunch.enitiy.Order;

/**
 * 10.10.12 : 22:26
 * User: sushka
 * формат csv: course.id;customer.id;count;date
 */
public class FileOrderDao extends FileDao<Order>{
    
    final static String FILE_NAME = "./db/order.csv";

    @Override
    protected String getFileName() {
        return FILE_NAME;
    }

    @Override
    protected String convertToCsv(Order persistent){
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        String date = sdf.format(persistent.getDate().getTime());
        return persistent.getMenuItemId()+";"+persistent.getCustomerId()+";"+persistent.getCount()+";"+date;
    }

    @Override
    protected Order parseCsv(String csvline) throws ParseException{
        //validating
        if (csvline.trim().length() == 0){
            throw new ParseException(csvline, 0);
        }
        String[] args = csvline.split(";");
        if (args.length != 4){
            throw new ParseException(csvline, 0);
        }
        int courseId    = Integer.parseInt(args[0].trim());
        int customerId  = Integer.parseInt(args[1].trim());
        int count       = Integer.parseInt(args[2].trim());
        Calendar date = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        date.setTime(sdf.parse(args[3].trim()));
        
        return new Order(courseId,customerId,count,date);
    }
}
